"""
通过 P 模式下的PNG 生成的 xml

xml
<data>
    <instance>
        <id>1</id>
        <contour>
            <x>60</x>
            <y>60</y>
        </contour>
        <type>2</type>
    </instance>
</data>

"""
import copy
import xml.etree.ElementTree as ET
import json
import os
import cv2
import numpy as np
from PIL import Image


png_folder_path = "/home/whj/桌面/tif"
target_path = "/home/whj/桌面/mask_xml/"
if not os.path.exists(target_path):
    os.makedirs(target_path)
# 遍历指定文件夹下的所有文件
for root, dirs, files in os.walk(png_folder_path):
    for file in sorted(files):
        try:
            xml_root = ET.Element('data')

            file_path = os.path.join(root, file)
            slide = Image.open(file_path)
            slide_arr = np.array(slide)
            # target_arr = (slide_arr == 1) + (slide_arr == 3) + (slide_arr == 4)
            type_list = [1, 3, 4]
            for index, type_value in enumerate(type_list):
                ins = ET.SubElement(xml_root, 'instance')
                id_ = ET.SubElement(ins, 'id')
                id_.text = str(index)

                tp = ET.SubElement(ins, 'type')
                tp.text = str(type_value)

                target_arr = (slide_arr == type_value)
                elements = []
                # 使用OpenCV的findContours函数找到所有连通域的边界
                contours, _ = cv2.findContours(np.array(target_arr, dtype=np.uint8), cv2.RETR_EXTERNAL,
                                               cv2.CHAIN_APPROX_TC89_L1)
                # 遍历每个标记的连通域，记录其坐标
                for i, contour in enumerate(contours):
                    points = []
                    if len(contour) < 10:
                        continue
                    contour = contour.reshape(-1, 2)
                    cont = ET.SubElement(ins, 'contour')
                    for point in contour:
                        x = int(point[0] * 64)
                        y = int(point[1] * 64)

                        x_ = ET.SubElement(cont, 'x')
                        x_.text = str(x)
                        y_ = ET.SubElement(cont, 'y')
                        y_.text = str(y)

            tree = ET.ElementTree(xml_root)
            file_name = target_path + file.split('.')[0] + '_mask.xml'
            tree.write(file_name)

        except Exception as e:
            print(f"Error decoding : {e}")
